<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- <el-tabs type="border-card">
        <el-tab-pane label="合同信息"> -->
          
          <el-row>
            <el-col :span="12">
              <el-form-item label="员工姓名" prop="userId">
                 <!-- 监听在绑定的时候,赋予userName -->
                <UserSelect @node-change="handleNodeChange"  :user-id="formData.userId"    v-model="formData.userId"  :disabled="updateDisabled || formData.userId" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同名称" prop="contractName">
                <el-input v-model="formData.contractName" placeholder="请输入合同名称" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="合同类别" prop="contractCategory">
                <el-select v-model="formData.contractCategory" placeholder="请选择合同类别" :disabled="updateDisabled">
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.OA_EMPLOYEE_CONTRACT_CATEGORY)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同类型" prop="contractType">
                <el-select v-model="formData.contractType" placeholder="请选择合同类型" :disabled="updateDisabled">
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.OA_EMPLOYEE_CONTRACT_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- <el-col :span="12">
              <el-form-item label="合同编码" prop="contractCode">
                <el-input v-model="formData.contractCode" placeholder="请输入合同编码" />
              </el-form-item>
            </el-col> -->
            <el-col :span="12">
              <el-form-item label="签约公司" prop="signingCompany">
                <el-input v-model="formData.signingCompany" placeholder="请输入签约公司" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="签订日期" prop="signingDate">
                <el-date-picker
                  v-model="formData.signingDate"
                  type="date"
                  value-format="x"
                  placeholder="选择签订日期"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            
            <el-col :span="12">
              <el-form-item label="合同开始时间" prop="effectiveStartDate">
                <el-date-picker
                  v-model="formData.effectiveStartDate"
                  type="date"
                  value-format="x"
                  placeholder="选择合同开始日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同结束日期" prop="effectiveEndDate">
                <el-date-picker
                  v-model="formData.effectiveEndDate"
                  type="date"
                  value-format="x"
                  placeholder="选择合同结束日期"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            
            <!-- <el-col :span="12">
              <el-form-item label="合同属性" prop="contractAttribute">
                <el-select v-model="formData.contractAttribute" placeholder="请选择合同属性">
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.OA_CONTRACT_ATTRIBUTE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col >
              <el-form-item label="合同金额(元)" prop="regularSalary">
                <el-input v-model="formData.regularSalary" type="number" placeholder="请输入合同金额(元)" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.contractCategory==1">
            <el-col :span="12">
              <el-form-item label="试用期月数" prop="probationMonths">
                <el-input v-model="formData.probationMonths" placeholder="请输入员工试用期月数" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="试用结束时间" prop="probationEndDate">
                <el-date-picker
                  v-model="formData.probationEndDate"
                  type="date"
                  value-format="x"
                  placeholder="选择试用结束时间"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- <el-col :span="12" v-if="formData.contractCategory==1">
              <el-form-item label="试用工资(元)" prop="probationSalary">
                <el-input v-model="formData.probationSalary" placeholder="请输入试用工资(元)" />
              </el-form-item>
            </el-col> -->
            
          </el-row>
      <el-form-item label="备注说明" prop="remarks">
        <el-input v-model="formData.remarks" placeholder="请输入备注说明" type="textarea" />
      </el-form-item>

        <el-form-item label="相关附件" >
          <OaFileManager :folderDisabled="true" :initial-file-ids="formData.files" @file-select-success="fileSelectScccess"  />
        </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { EmployeeContractsApi, EmployeeContractsVO } from '@/api/oa/employeecontracts'
import UserSelect  from '@/views/system/user/UserSelect.vue'

/** 员工合同信息 表单 */
defineOptions({ name: 'EmployeeContractsForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  contractCategory: undefined,
  contractType: undefined as number | undefined,
  userId: undefined,
  userName: undefined,
  signingCompany: undefined,
  contractName: undefined,
  contractCode: undefined,
  signingDate: undefined,
  effectiveStartDate: undefined,
  effectiveEndDate: undefined,
  contractAttribute: undefined,
  renewalStatus: undefined,
  modificationStatus: undefined,
  renewalId: undefined,
  renewalDate: undefined,
  modificationId: undefined,
  modificationDate: undefined,
  probationMonths: undefined,
  probationEndDate: undefined,
  probationSalary: undefined,
  regularSalary: undefined,
  remarks: undefined,
  attachmentPath: undefined,
})
const formRules = reactive({
  // contractCategory: [{ required: true, message: '合同类别不能为空', trigger: 'change' }],
  // contractType: [{ required: true, message: '合同类型不能为空', trigger: 'change' }],
  // userId: [{ required: true, message: '关联员工ID不能为空', trigger: 'blur' }],
  // userName: [{ required: true, message: '员工姓名不能为空', trigger: 'blur' }],
  // signingCompany: [{ required: true, message: '签约主体公司不能为空', trigger: 'blur' }],
  // contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  // // contractCode: [{ required: true, message: '合同编码不能为空', trigger: 'blur' }],
  // signingDate: [{ required: true, message: '签订日期不能为空', trigger: 'blur' }],
  // effectiveStartDate: [{ required: true, message: '合同开始日期不能为空', trigger: 'blur' }],
  // contractAttribute: [{ required: true, message: '合同属性不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref
const updateDisabled =ref(false)
const fileSelectScccess = (fileIds: string[]) => {
  formData.value.files = fileIds.join(',')
}


/** 打开弹窗 */
const open = async (type: string, id?: number, userId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const info = await EmployeeContractsApi.getEmployeeContracts(id)
      if(type=='续签' || type=='变更'){
        formType.value = 'create'
        dialogTitle.value = type + '合同'
        updateDisabled.value = true
        formData.value.id  = undefined
        formData.value.contractCategory = info.contractCategory

        formData.value.userId = info.userId
        formData.value.userName = info.userName

        if(type=='续签'){
          formData.value.contractType = 2
          formData.value.renewalId = info.id
        }else if(type=='变更'){
          formData.value.contractType = 3
          formData.value.modificationId = info.id
        }
      }else{
        formData.value = info
      }
    } finally {
      formLoading.value = false
    }
  }else{
    if(userId){
      formData.value.userId = userId
    }
  }
  
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as EmployeeContractsVO
    if (formType.value === 'create') {
      await EmployeeContractsApi.createEmployeeContracts(data)
      message.success(t('common.createSuccess'))
    } else {
      await EmployeeContractsApi.updateEmployeeContracts(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    contractCategory: undefined,
    contractType: undefined,
    userId: undefined,
    userName: undefined,
    signingCompany: undefined,
    contractName: undefined,
    contractCode: undefined,
    signingDate: undefined,
    effectiveStartDate: undefined,
    effectiveEndDate: undefined,
    contractAttribute: undefined,
    renewalStatus: undefined,
    modificationStatus: undefined,
    renewalId: undefined,
    renewalDate: undefined,
    modificationId: undefined,
    modificationDate: undefined,
    probationMonths: undefined,
    probationEndDate: undefined,
    probationSalary: undefined,
    regularSalary: undefined,
    remarks: undefined,
    attachmentPath: undefined,
  }
  formRef.value?.resetFields()
}

/** 员工被点击事件 */
const handleNodeChange = async (row) =>{
  formData.value.userId = row.id
  formData.value.userName = row.nickname
  console.log('选中的员工ID:', formData.value.userId)
  console.log('选中的员工昵称:', formData.value.userName)
}
</script>
